<?php

/**
 * Тэги.
 */
class TagsModel extends DbModel {

    protected $_name = 'tags_links';

    public function updateTags($tags, $object, $oid) {
        //Удаляем ссылки
        $this->delete('object = "' . $object . '" AND oid = ' . $oid);
        $filter = new Zend_Filter_StripTags();

        $tags = explode(',', $tags);
        foreach ($tags as $tag) {
            $tagName = trim($filter->filter($tag));
            if ($tagName <> '') {
                $tag = $this->getTag($tagName, $object);
                if (!empty($tag)) {
                    $tag_id = $tag->id;
                } else {
                    $tag_id = $this->newTag($tagName, $object);
                }
                $this->insert(array('tid' => $tag_id, 'oid' => $oid, 'object' => $object));
            }
        }
    }

    public function removeTags($object, $oid) {
        $sql = $this->delete('object = "'.$object.'" AND oid = ' . $oid);
        return true;
    }

    public function getTag($tag, $object = '') {
        $sql = $this->_db->select()->from(PREFIX . 'tags')->where('tag = ?', $tag);
        if ($object <> '')
            $sql->where('object = "'.$object . '"');
        $tag = $this->_db->fetchRow($sql);
        return $tag;
    }
    
    public function getTagById($tid, $object = '') {
        $sql = $this->_db->select()->from(PREFIX . 'tags')->where('id = ?', $tid);
        if ($object <> '')
            $sql->where('object = "'.$object . '"');
        $tag = $this->_db->fetchRow($sql);
        return $tag;
    }

    public function getTags($object = '') {
        $sql = $this->_db->select()->from(PREFIX . 'tags',array('id', 'tag'))->order('tag ASC');
        if ($object <> '')
            $sql->where('object = "' . $object . '"');
        $tags = $this->_db->fetchPairs($sql);
        return $tags;
    }

    public function getObjectTags($object, $oid, $line = false) {
        $sql = $this->_db->select()
                        ->from(array('t' => PREFIX . 'tags'), array('t.*'))
                        ->join(array('l' => PREFIX . 'tags_links'),
                                't.id = l.tid')
                        ->where('l.object = "' . $object . '"')
                        ->where('l.oid = ' . $oid)
                        ->order('t.tag ASC');
        $tags = $this->_db->fetchPairs($sql);
        if ($line) {
            $string = implode(', ', $tags);
            return $string;
        } else
            return $tags;
    }

    public function newTag($tag, $object) {
        $this->_db->insert(PREFIX . 'tags', array('tag' => $tag, 'object' => $object ));
        $id = $this->_db->lastInsertId();
        return $id;
    }

}
